package com.example.club.test.flow
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flatMapConcat

import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.zip
import kotlinx.coroutines.launch

class FlowViewModel:ViewModel() {
    val flow1 = flow {
        var time = 0
        while (true) {
            emit(time)
            delay(1000)
            time++
        }
    }

    val flow2 = flow {
        var time = 0
        while (true) {
            emit(time)
            delay(1000)
            time --
        }
    }

    /**
     * 获得用户信息：2个接口串连
     */
    fun getUserData(){
        viewModelScope.launch {
            sendGetTokenRequest()
                .flatMapConcat { token ->
                    sendGetUserInfoRequest(token)
                }.collect{userInfo->
                    Log.d("TAG", "getUserData: $userInfo")
                }
        }
    }
    var weather:Weather = Weather()

    fun getWeatherData(){
        viewModelScope.launch {
            sendRealtimeWeatherRequest()
                .zip(sendSevenDaysWeatherRequest()){realtimeWeather, sevenDaysWeather ->
                    weather.real = realtimeWeather
                    weather.seven = sevenDaysWeather
                    weather
                }
                .zip(sendWeatherBackgroundImageRequest()){ weather, backgroundImage ->
                    weather.backImage = backgroundImage
                    weather
                }.collect{ weather ->
                    Log.d("TAG", "getWeatherData: $weather")

                }

        }
    }

    data class Weather(
        var real:String = "",
        var seven:String = "",
        var backImage:String = ""
    )
    /**
     * 获得token
     */
    fun sendGetTokenRequest(): Flow<String> = flow {
        emit("token")
    }.flowOn(Dispatchers.IO)

    /**
     * 根据token获得用户信息
     */
    fun sendGetUserInfoRequest(token: String): Flow<String> = flow {
        emit("用户信息")
    }.flowOn(Dispatchers.IO)

    /**
     * 请求当前
     */
    fun sendRealtimeWeatherRequest(): Flow<String> = flow {
        emit("当前天气")
    }
    /**
     * 请求未来7天
     */
    fun sendSevenDaysWeatherRequest(): Flow<String> = flow {
        emit("未来7天")
    }

    /**
     * 请求未来1个月
     */
    fun sendWeatherBackgroundImageRequest(): Flow<String> = flow {
        emit("未来一个月")
    }
}